package com.gzz.orchid.context.infrastructure.support.listener;

import com.gzz.orchid.common.boot.mybatis.auditor.InsertHandler;
import com.gzz.orchid.common.boot.mybatis.auditor.UpdateHandler;
import com.gzz.orchid.context.infrastructure.persistence.AbstractPojo;

import java.time.LocalDateTime;

/**
 * MyBatis Insert/Update Listener
 * @author higmd
 */
public class MyBatisAuditHandler implements InsertHandler, UpdateHandler {
    @Override
    public void onInsert(Object entity) {
        if (entity instanceof AbstractPojo po) {
            po.setVersion(0L);
            po.setDeleted(Boolean.FALSE);
            po.setCreatedBy("Auto Inserter");
            po.setUpdatedBy("Auto Inserter");
            po.setCreatedOn(LocalDateTime.now());
            po.setUpdatedOn(LocalDateTime.now());
        }
    }

    @Override
    public void onUpdate(Object entity) {
        if (entity instanceof AbstractPojo po) {
            po.setUpdatedBy("Auto Inserter");
            po.setUpdatedOn(LocalDateTime.now());
        }
    }
}
